package day5.homework;

import java.lang.reflect.Field;

public class TransferField {
    private String name;
    public Integer id;
    //通过反射编写一个通用方法实现对象属性赋值功能，能够将一个对象的
    //属性值复制到另一个对象(同名属性)
    //参数1：获取属性对象  参数2：被赋值的对象  参数3：属性名
    public static void fieldTransfer(Object obj1,Object obj2,String name){
        try {
            Class c = obj1.getClass();
            Field f = c.getDeclaredField(name);
            f.setAccessible(true);
            Object value = f.get(obj1);
            f.set(obj2,value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        TransferField tf1 = new TransferField();
        TransferField tf2 = new TransferField();
        tf1.name = "陈平安";
        fieldTransfer(tf1,tf2,"name");
        System.out.println(tf2.name);
    }
}
